/* Copyright (c) 2009-2010, Sean A.O. Harney <sharney3@gmail.com> */

// debug related functions

#include "omf.h"

/* prototypes */
void _debug_printf(va_list argp, const char *fmt);

// globals
int debug_level;
FILE *debug_file = NULL;


// filepath=NULL for stderr
void debug_init(signed int level, const char *filepath)
{
    debug_level = level;
    if (debug_level > 3)
	debug_level = 3;


    if (debug_level > DEBUG_LEVEL_QUIET)
	fprintf(stderr, "Logging (level %d) debugging information to %s\n",
		debug_level, filepath == NULL ? "stderr" : filepath);

    if (filepath != NULL)
      {
	  debug_file = fopen(filepath, "a+");	// for debugging information
	  if (debug_file == NULL)
	      fatal_error_perror(filepath);
    } else
	debug_file = stderr;
}

void debug_close(void)
{
    if (debug_file == NULL)
	return;

    fclose(debug_file);		//bug:If using stderr, it closes stderr
    debug_file = NULL;
}



// level >= 0 > quiet
void debug_unquiet_printf(const char *fmt, ...)
{
    va_list argp;

    if (debug_level == DEBUG_LEVEL_QUIET || debug_file == NULL)	// debug might not be on but still be unquiet (no -q)
	return;


    va_start(argp, fmt);	//fmt is last before the elipsis ...
    vfprintf(debug_file, fmt, argp);
    fflush(debug_file);
    va_end(argp);
}

// level >= 1 > quiet 
void debug1_printf(const char *fmt, ...)
{
    va_list argp;

    if (debug_level <= 0 || debug_file == NULL)	// debug not on or not init'ed.
	return;


    va_start(argp, fmt);	//fmt is last before the elipsis ...
    vfprintf(debug_file, fmt, argp);
    fflush(debug_file);
    va_end(argp);
}

// debug >= 2
void debug2_printf(const char *fmt, ...)
{
    va_list argp;

    if (debug_level <= 1 || debug_file == NULL)	// debug not on
	return;

    va_start(argp, fmt);	//fmt is last before the elipsis ...
    vfprintf(debug_file, fmt, argp);
    fflush(debug_file);
    va_end(argp);
}
